import requests
from bs4 import BeautifulSoup
import os

# 示例code数组
codes = ['5227', '3059', '6095'
    ,'5859','4416','1456','5923','5216'
    ,'5223','4840','2881','4813','4329','5860','2882','3339'
    ,'4586','4258','5217','4258','4961','2989','4894','3131','3001'
    ,'1101','5257','1609','5001','5888','4384'
    ,'2843','3478','5819','5409','1616','4357'
    ,'4540','5008','5248','4899','4300','3049','3077','1820','3504','5290','5579','8979','3455','4981','302','2887','4076','4797','4638','5847','1833'
    ,'4363','3762','1255','1254'
    ,'4499','5047','4320','5896'
    ,'4814','3101','4426','3503']

# 基础URL
base_url = 'https://www.dongchedi.com/auto/series/score/{}-x-x-x-x-x'

# 创建保存评论的根目录
root_dir = 'comments'
if not os.path.exists(root_dir):
    os.makedirs(root_dir)

# 爬取数据
for code in codes:
    url = base_url.format(code)
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')

    # 获取品牌名称
    brand_element = soup.select_one(
        'html > body > div#__next > div.tw-flex > div.new-main.new > div.breadcrumb_wrap__2GLeU > p.breadcrumb_inner__3ahw2.breadcrumb_hide-line__3gPEY > span.pos-item.icon.icon-arrow-ic-r > a')
    if brand_element:
        brand_name = brand_element.get_text(strip=True)
    else:
        print(f"无法找到品牌名称，页面URL: {url}")
        continue

    # 获取车型名称
    model_element = soup.select(
        'html > body > div#__next > div.tw-flex > div.new-main.new > div.breadcrumb_wrap__2GLeU > p.breadcrumb_inner__3ahw2.breadcrumb_hide-line__3gPEY > span.pos-item.icon.icon-arrow-ic-r > a')
    if len(model_element) > 1:
        model_name = model_element[1].get_text(strip=True)
    else:
        print(f"无法找到车型名称，页面URL: {url}")
        continue

    # 获取评论内容
    comments_section = soup.select_one(
        'html > body > div#__next > div.tw-flex > div.new-main.new > div:nth-of-type(3) > section.tw-grid.tw-gap-12.tw-grid-cols-40 > section.tw-col-span-40.md\\:tw-col-span-29 > div.car-model-filter > div.content-wrapper.tw-flex.tw-bg-white.tw-mt-2.tw-py-12.tw-pl-16 > div.content-right > div.tw-flex > div.tag-list.tw-flex.tw-flex-1.tw-flex-wrap.tw--mt-12.tw-overflow-hidden')
    if comments_section:
        comments = comments_section.get_text(separator='\n', strip=True)
    else:
        print(f"无法找到评论内容，页面URL: {url}")
        continue

    # 创建品牌和车型目录
    brand_dir = os.path.join(root_dir, brand_name)
    if not os.path.exists(brand_dir):
        os.makedirs(brand_dir)

    # 保存评论到文件
    file_path = os.path.join(brand_dir, f"{model_name}.txt")
    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(comments)

    print(f"成功保存评论到文件: {file_path}")
